#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdlib>
#include <cstring>
#include "Thread.hpp"
#include"Comm.hpp"

using namespace ThreadModule;
using namespace std;
int InitClient(std::string &serverip, uint16_t serverport, struct sockaddr_in *server)
{
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cerr << "socket error" << endl;
        return -1;
    }
     memset(&server, 0, sizeof(struct sockaddr_in));
    server->sin_family = AF_INET;
    server->sin_port = htons(serverport);
    server->sin_addr.s_addr = inet_addr(serverip.c_str());
    return sockfd;
}
void Usage(string proc)
{
    cout << "Usage:\n\t" << "local_ip local_port\n"
         << endl;
}

void recvmessage(int sockfd, std::string name)
{
    int fd=OpenDev("/dev/pts/1",O_WRONLY);
    while (1)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buffer[1024];
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
        if (n > 0)
        {
            buffer[n] = 0;
            //printf("%s | %s\n",name.c_str(),buffer);
           // cout <<name <<" | "<< buffer << endl;
           write(fd,buffer,strlen(buffer));
        }
    }
}

void sendmessage(int sockfd, struct sockaddr_in &server, std::string name)
{
    std::string message;
    while (1)
    {
        //cout << name << "| Please Enter# ";
        printf("%s | Enter# ",name.c_str());
        fflush(stdout);
        getline(cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
    }
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    struct sockaddr_in serveraddr;
    int sockfd = InitClient(serverip, serverport, &serveraddr);
    if (sockfd == -1)
        return 1;

    hander_message_t r = std::bind(&recvmessage, sockfd, std::placeholders::_1);
    hander_message_t s = std::bind(&sendmessage, sockfd, serveraddr, std::placeholders::_1);
    Thread Recver(r, "recver");
    Thread Sender(s, "sender");

    Recver.Start();
    Sender.Start();

    Recver.Join();
    Sender.Join();
    // string message;
    // while (1)
    // {
    //     cout << "Please Enter# ";
    //     getline(cin, message);
    //     sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
    //     struct sockaddr_in peer;
    //     socklen_t len=sizeof(peer);
    //     char buffer[1024];
    //     ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer,&len);
    //     if(n>0)
    //     {
    //         buffer[n]=0;
    //         cout<<"server echo# "<<buffer<<endl;
    //     }
    // }
    return 0;
}